import React, { useEffect, useRef, useState } from "react";
import {
  blackCustomer,
  getAllCustomerLevels,
  getCustomerDetail,
  getCustomers,
  modifyCustomerLevel,
  transferCustomer,
  updateCustomerRemark,
  updateRuleState
} from "@/services/customer/customer";
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProFormSelect,
  ProFormTextArea,
  ProFormTreeSelect,
  ProTable
} from "@ant-design/pro-components";
import {
  Button,
  Checkbox,
  Col,
  DatePicker,
  message,
  Row,
  Spin,
  Switch,
  Tabs,
  Tooltip,
  TreeDataNode,
  TreeSelect,
  Table, Space,
} from "antd";
import { getDepartmentMembers, getDepartments } from "@/services/department/department";
import moment from 'moment';
import { useModel } from "@@/exports";
import { DEPARTMENT_MANAGE, SALES_MANAGE } from "@/global.style";
import { getGroups } from "@/services/group/group";

const CustomerManage = () => {
  const [loading, setLoading] = useState(false);
  const { initialState, setInitialState } = useModel('@@initialState');

  const actionRef = useRef<ActionType>();
  const remarkRef = useRef();
  const modifyRef = useRef<ActionType>()
  const quizRef = useRef();
  const inviteRef = useRef();
  const levelRef = useRef();

  const [modal, setModal] = useState(false)
  const [memoModal, setMemoModal] = useState(false)
  const [levelModal, setLevelModal] = useState(false)
  const [moveModal, setMoveModal] = useState(false)
  const [record, setRecord] = useState(null)

  const [departments, setDepartments] = useState([])
  const [sales, setSales] = useState([])
  const [wechatGroups, setWechatGroups] = useState([])
  const [detail, setDetail] = useState(null)
  const [levelMap, setLevelMap] = useState([])
  const [levels, setLevels] = useState([])
  const [customers, setCustomers] = useState([])
  const [chkAll, setChkAll] = useState(false)

  const [currentIndex, setCurrentIndex] = useState(0)
  const [size, setSize] = useState(10)
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const shouldShowModifyRecord = (roles) => {
    const restrictedRoles = [DEPARTMENT_MANAGE, SALES_MANAGE];
    return !roles.some(role => restrictedRoles.includes(role));
  }
  const getDepartmentList = async () => {
    const res = await getDepartments()
    if (res.code !== 1) {
      message.error('获取部门列表失败,' + res.msg)
      return
    }
    console.log('all departments', res.data)
    const buildTreeNodes = async (departments) => {
      const findChildren = (parent) => {
        return departments.filter(department => department.parentId === parent.wxDid)
          .map(department => {
            const item: TreeDataNode = {
              key: department.wxDid,
              value: department.wxDid,
              title: department.name,
              parentId: department.parentId,
              children: findChildren(department)
            }
            return item
          })
      };
      const rootNodes = departments.filter(department => department.parentId === 0)
        .map(department => {
          const item: TreeDataNode = {
            key: department.wxDid,
            value: department.wxDid,
            title: department.name,
            parentId: department.parentId,
            children: findChildren(department)
          }
          return item
        });
      return rootNodes;
    }
    const departmentSelectData = await buildTreeNodes(res.data);
    setDepartments(departmentSelectData)
  }
  const getLevelList = async () => {
    const msg = await getAllCustomerLevels()
    console.log('all levelMap', msg.data)
    const levelMap = {}
    msg.data.forEach(level => {
      levelMap[level.levelName] = level
    })
    setLevelMap(levelMap)
    const levels = []
    msg.data.forEach(level => {
      levels.push({
        label: level.levelName,
        value: level.id
      })
    })
    setLevels(levels)
  }
  const getSalesList = async () => {
    const res = await getDepartmentMembers({
      page: 1,
      size: 9999,
    })
    if (res.code !== 1) {
      message.error('获取销售列表失败,' + res.msg)
      return
    }
    console.log('all sales', res)
    const sales = []
    res.data.records.forEach(sale => {
      sales.push({
        title: sale.name,
        label: sale.name,
        value: sale.wxUid
      })
    })
    setSales(sales)
  }
  const getWechatGroups = async () => {
    const res = await getGroups({ page: 1, size: 9999 })
    if (res.code !== 1) {
      message.error('获取微信群列表失败,' + res.msg)
      return
    }
    console.log('all wechat groups', res)
    const wechatGroups = []
    res.data.records.forEach(group => {
      wechatGroups.push({
        title: group.groupName,
        label: group.groupName,
        value: group.wxGid,
      })
    })
    setWechatGroups(wechatGroups)
  }

  useEffect(() => {
    // getCustomerList()
    getDepartmentList()
    getLevelList()
    getSalesList()
    getWechatGroups()
  }, [])

  const { RangePicker } = DatePicker;
  const columns: ProColumns<CUSTOMER.Customer>[] = [
    {
      title: '选择',
      key: 'checkbox',
      valueType: 'checkbox',
      hideInSearch: true,
      render: (_, record) => (
        <Checkbox
          checked={selectedRowKeys.includes(record.unionid)}
          onChange={(e) => {
            console.log('checkbox', e, record)
            if (e.target.checked) {
              setSelectedRowKeys([...selectedRowKeys, record.unionid])
              if (selectedRowKeys.length + 1 >= customers.length) {
                setChkAll(true)
              }
            } else {
              setSelectedRowKeys(selectedRowKeys.filter(key => key !== record.unionid))
              setChkAll(false)
            }
          }}
        />
      ),
    },
    {
      title: '头像',
      key: 'avatarUrl',
      dataIndex: 'avatarUrl',
      hideInSearch: true,
      render: (text, record) => {
        return record.avatarUrl ? <img src={record.avatarUrl} style={{ width: '50px', height: '50px' }} alt={''} /> : ''
      }
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
    },
    {
      title: '用户级别',
      dataIndex: 'levelName',
      key: 'levelName',
      hideInSearch: true,
      render: (text, record) => {
        // 使用Tooltip组件来显示提示
        return <Tooltip title={levelMap && levelMap[text] ? levelMap[text].description : ''}> <a onClick={async () => {
          setRecord(record)
          setLevelModal(true)
        }}>
          {text}
        </a></Tooltip>
      }
    },
    {
      title: '归属门店',
      dataIndex: 'wxDid',
      key: 'wxDid',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        // 当表单项被渲染时，使用TreeSelect组件
        return <TreeSelect
          {...rest}
          treeData={departments}
          placeholder="请选择部门"
          treeDefaultExpandAll
        />;
      },
    }, {
      title: '归属门店',
      dataIndex: 'departmentName',
      key: 'departmentName',
      hideInSearch: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        // 当表单项被渲染时，使用TreeSelect组件
        return <TreeSelect
          {...rest}
          treeData={departments}
          placeholder="请选择部门"
          treeDefaultExpandAll
        />;
      },
    },
    {
      title: '归属微信群',
      dataIndex: 'wechatGroupName',
      key: 'wechatGroupName',
      hideInSearch: true,
    },
    {
      title: '归属微信群',
      dataIndex: 'wxGid',
      key: 'wxGid',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        // 当表单项被渲染时，使用TreeSelect组件
        return <TreeSelect
          {...rest}
          treeData={wechatGroups}
          placeholder="请选择微信群"
          treeDefaultExpandAll
        />;
      },
    },
    {
      title: '绑定销售',
      key: 'salesName',
      dataIndex: 'salesName',
      hideInSearch: true,
    }, {
      title: '绑定销售',
      key: 'salesWxUid',
      dataIndex: 'salesWxUid',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        // 当表单项被渲染时，使用TreeSelect组件
        return <TreeSelect
          {...rest}
          treeData={sales}
          placeholder="请选择销售"
          treeDefaultExpandAll
        />;
      },
    },
    {
      title: '答题数量',
      dataIndex: 'quizCount',
      key: 'quizCount',
      hideInSearch: true,
      sorter: true
    },
    {
      title: '邀请人数',
      key: 'inviteCount',
      dataIndex: 'inviteCount',
      hideInSearch: true,
      sorter: true
    },
    {
      title: '累计获得红包',
      dataIndex: 'totalRedPacket',
      key: 'totalRedPacket',
      hideInSearch: true,
      sorter: true
    },
    {
      title: '注册时间',
      dataIndex: 'registerTime',
      key: 'registerTime',
      valueType: 'dateRange',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        // 当表单项被渲染时，使用RangePicker组件
        if (type === 'form') {
          return <RangePicker showTime={{ format: 'HH:mm:ss' }} format="YYYY-MM-DD HH:mm:ss" {...rest} />;
        }
        // 使用默认渲染逻辑
        return defaultRender(_);
      },
    },
    {
      title: '注册时间',
      dataIndex: 'registerTime',
      key: 'registerTime',
      hideInSearch: true,
      render: (text, record) => {
        return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : ' - '
      }
    },
    {
      title: '添加销售时间',
      dataIndex: 'addSalesTime',
      key: 'addSalesTime',
      valueType: 'dateRange',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        // 当表单项被渲染时，使用RangePicker组件
        if (type === 'form') {
          return <RangePicker showTime={{ format: 'HH:mm:ss' }} format="YYYY-MM-DD HH:mm:ss" {...rest} />;
        }
        // 使用默认渲染逻辑
        return defaultRender(_);
      },
    }, {
      title: '添加销售时间',
      dataIndex: 'addSalesTime',
      key: 'addSalesTime',
      hideInSearch: true,
      render: (text, record) => {
        return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : ' - '
      }
    }, {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      hideInSearch: true
    },  {
      title: '邀请限制',
      dataIndex: 'blacklist',
      key: 'blacklist',
      hideInSearch: true,
      render: (text, record) => {
        return <Switch checked={true} onChange={async (checked: boolean, event: Event) => {
          console.log('switch', record)
          setLoading(true)
          const params = {
            unionid: record.unionid,
            ruleState: 0
          }
          const res = await updateRuleState(params)
          setLoading(false)

          if (res.code === 1) {
            actionRef.current?.reload()
            message.success('操作成功')
          } else {
            message.error('操作失败')
          }
        }} />
      }
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a key="editable" onClick={async () => {
          setLoading(true)
          const res = await getCustomerDetail({
            wxUid: record.unionid
          })
          console.log('get customer detail', res)
          setDetail(res.data)
          setRecord(record)
          setModal(true)
        }}>
          查看用户详情
        </a> 
      ],
    },
  ]
  const { TabPane } = Tabs;
  const quizColumns = [
    {
      title: '类别',
      dataIndex: 'audioCategoryName',
    }, {
      title: '标号',
      dataIndex: 'tag',
    }, {
      title: '播放时间',
      dataIndex: 'playTime',
      render: (text, record) => {
        return moment(text).format('YYYY-MM-DD HH:mm:ss')
      }
    }, {
      title: '答题时间',
      dataIndex: 'quizTime',
      render: (text, record) => {
        return moment(text).format('YYYY-MM-DD HH:mm:ss')
      }
    }, {
      title: '答题状态',
      dataIndex: 'quizStatusDesc',
    }, {
      title: '答题红包',
      dataIndex: 'redPacketAmount',
    }
  ]
  const inviteColumns = [
    {
      title: '邀请用户昵称',
      dataIndex: 'nickname',
    }, {
      title: '答题时间',
      dataIndex: 'lastQuizTime',
      render: (text, record) => {
        return moment(text).format('YYYY-MM-DD HH:mm:ss')
      }
    }, {
      title: '邀约红包',
      dataIndex: 'redPacketAmount',
    }
  ]
  const changeColumns = [
    {
      title: '修改类型',
      dataIndex: 'changeType',
      valueEnum: {
        1: { text: '用户级别' },
        0: { text: '备注' },
      }
    }, {
      title: '修改时间',
      dataIndex: 'modifiedTime',
      render: (text, record) => {
        return moment(text).format('YYYY-MM-DD HH:mm:ss')
      }
    }, {
      title: '修改人',
      dataIndex: 'modifierNickname',
    }, {
      title: '修改内容',
      dataIndex: 'content',
    }
  ]

  // const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
  //   console.log('selectedRowKeys changed: ', newSelectedRowKeys);
  //   setSelectedRowKeys(newSelectedRowKeys);
  // };

  return (
    <PageContainer>
      <Spin spinning={loading} tip="加载中...">
        <ProTable
          rowKey={'key'}
          columns={columns}
          actionRef={actionRef}
          // rowSelection={{
          //   // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
          //   // 注释该行则默认不显示下拉选项
          //   selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          //   defaultSelectedRowKeys: [],
          //   onChange: onSelectChange,
          // }}
          cardBordered
          request={async (params, sort, filter) => {
            setSelectedRowKeys([])
            setChkAll(false)
            console.log(sort)
            if (sort.quizCount === 'ascend') {
              params.quizOrder = 'desc'
            } else if (sort.quizCount === 'descend') {
              params.quizOrder = 'asc'
            }
            if (sort.inviteCount === 'ascend') {
              params.inviteOrder = 'desc'
            } else if (sort.inviteCount === 'descend') {
              params.inviteOrder = 'asc'
            }
            if (sort.totalRedPacket === 'ascend') {
              params.redOrder = 'desc'
            } else if (sort.totalRedPacket === 'descend') {
              params.redOrder = 'asc'
            }
            console.log('params', params)


            const reqParams = {
              ...params,
              page: currentIndex,
              size: params.pageSize,
            }
            if (reqParams.registerTime) {
              reqParams.registerTimeStart = String(params.registerTime).split(',')[0]
              reqParams.registerTimeEnd = String(params.registerTime).split(',')[1]
            }
            if (reqParams.addSalesTime) {
              reqParams.addSalesTimeStart = String(params.addSalesTime).split(',')[0]
              reqParams.addSalesTimeEnd = String(params.addSalesTime).split(',')[1]
            }
            reqParams.ruleState=1
            const res = await getCustomers(reqParams)
            console.log('get customers list', res)
            if (res.code !== 1) {
              message.error('获取用户列表失败,' + res.msg)
              return {
                data: [],
                success: false,
                total: 0
              }
            }
            setCustomers(res.data.records)
            return {
              data: res.data.records,
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: res.data.total,
            };
          }}
          pagination={{
            // pageSize: size,
            showSizeChanger: true,
            onChange: (page) => setCurrentIndex(page),
          }}
          dateFormatter="string"
          // toolbar={{
          //   title: <Checkbox key='chk_all' checked={chkAll} onChange={(e) => {
          //     console.log('checkbox', e.target.checked)
          //     setChkAll(e.target.checked)
          //     if (e.target.checked) {
          //       const keys = customers.map(customer => customer.unionid)
          //       setSelectedRowKeys(keys)
          //     } else {
          //       setSelectedRowKeys([])
          //     }
          //   }}>全选</Checkbox>,
          // }}
          // toolBarRender={() => shouldShowModifyRecord(initialState.currentUser.roles) && ([
          //   <Button
          //     key="button"
          //     onClick={() => {
          //       if (selectedRowKeys.length === 0) {
          //         message.error('请先选择用户')
          //         return
          //       }
          //       setMoveModal(true)
          //     }}
          //     type="primary"
          //   >
          //     批量转移顾客
          //   </Button>,
          // ])}
        />
        <ModalForm
          title="用户详情"
          open={modal}
          onOpenChange={(open) => {
            setModal(open)
            quizRef.current?.reload()
            inviteRef.current?.reload()
            modifyRef.current?.reload()
            setLoading(false)
          }}
          onFinish={async (values) => {
            console.log('edit customer', values)
            return true
          }}
          submitter={false}
        >
          <Row>
            <Col span={8}>微信昵称：{detail ? detail.nickname : ''}</Col>
            <Col span={8}>归属门店：{detail ? detail.departmentName : ''}</Col>
            <Col span={8}>归属微信群：{detail ? detail.wechatGroupName : ''}</Col>
          </Row>

          <Row>
            <Col
              span={8}>注册时间：{detail && detail.registerTime ? moment(detail.registerTime).format('YYYY-MM-DD HH:mm:ss') : ' - '}</Col>
            <Col
              span={8}>入群时间：{detail && detail.joinGroupTime ? moment(detail.joinGroupTime).format('YYYY-MM-DD HH:mm:ss') : ' - '}</Col>
            <Col span={8}></Col>
          </Row>
          <Row>
            <Col span={8}>累计答题：{detail ? detail.quizCount : ''}</Col>
            <Col span={8}>累计邀请：{detail ? detail.inviteCount : ''}</Col>
            <Col span={8}>累计获得红包：{detail ? detail.totalRedPacket : ''}</Col>
          </Row>
          <Row>
            <Col span={8}>邀请人：{detail ? detail.inviterName : ''}</Col>
            <Col span={8}>邀请人ID：{detail ? detail.inviterUnionid : ''}</Col>
            <Col span={8}>用户级别：{detail ? detail.levelName : ''}</Col>
          </Row>
          <Row>
            <Tabs>
              <TabPane tab="答题一览" key="1">
                <ProTable
                  actionRef={quizRef}
                  key="departmentName"
                  search={false}
                  columns={quizColumns}
                  request={async () => {
                    console.log('quizs', detail.quizs)
                    return {
                      data: detail.quizs,
                      success: true,
                      total: detail.quizs.length
                    }
                  }}
                  pagination={false}
                  toolBarRender={false}
                />
              </TabPane>
              <TabPane tab="邀请一览" key="2">
                <ProTable actionRef={inviteRef} search={false} columns={inviteColumns} request={async () => {
                  return {
                    data: detail.invites,
                    success: true,
                    total: detail.invites.length
                  }
                }} pagination={false} toolBarRender={false} />
              </TabPane>
              {shouldShowModifyRecord(initialState.currentUser.roles) && (<TabPane tab="修改记录" key="3">
                <ProTable actionRef={modifyRef} search={false} columns={changeColumns} request={async () => {
                  return {
                    data: detail.changeRecords,
                    success: true,
                    total: detail.changeRecords.length
                  }
                }} pagination={false} toolBarRender={false} />
              </TabPane>)
              }
            </Tabs>
          </Row>
        </ModalForm>

        <ModalForm
          formRef={remarkRef}
          title="维护备注"
          open={memoModal}
          onOpenChange={(open) => {
            setMemoModal(open)
            remarkRef.current?.setFieldsValue({
              remark: record.remark
            })
          }}
          onFinish={async (values) => {
            console.log('edit customer', values)
            const params: CUSTOMER.UpdateCustomerRemarkParams = {
              remark: values.remark,
              unionid: record.unionid
            }
            const res = await updateCustomerRemark(params)
            if (res.code === 1) {
              message.success('操作成功')
              setMemoModal(false)
              actionRef.current?.reload()
              modifyRef.current?.reload()
              return true
            } else {
              message.error('操作失败')
              return false
            }
          }}
        >
          <ProFormTextArea name="remark" placeholder="请输入备注" />
          <div>填写客户联系方式、地址等</div>
        </ModalForm>
        <ModalForm
          formRef={levelRef}
          title="调整用户级别"
          open={levelModal}
          onOpenChange={(open) => {
            setLevelModal(open)
            levelRef.current?.setFieldsValue({
              level: record.levelId
            })
          }}
          onFinish={async (values) => {
            console.log('edit customer', values)
            const params = {
              unionid: record.unionid,
              levelId: values.level
            }
            const res = await modifyCustomerLevel(params)
            if (res.code !== 1) {
              message.error('操作失败')
              return false
            } else {
              message.success('操作成功')
              setLevelModal(false)
              actionRef.current?.reload()
            }
          }}
        >
          <ProFormSelect
            name="level"
            label="用户级别"
            options={levels}
            placeholder="请选择用户级别"
            rules={[{ required: true, message: '请选择用户级别' }]}
          />
        </ModalForm>
        <ModalForm
          title="转移用户"
          open={moveModal}
          onOpenChange={setMoveModal}
          onFinish={async (values) => {
            console.log('edit customer', values)
            console.log('selectedRowKeys', selectedRowKeys)
            selectedRowKeys.forEach(async (unionid) => {
              const params = {
                unionid: unionid,
                wxUid: values.sale
              }
              const res = await transferCustomer(params)
              if (res.code !== 1) {
                message.error(`转移失败${unionid}`)
                return false
              }
              actionRef.current?.reload()
              setSelectedRowKeys([])
            })
            return true
          }}
        >
          <ProFormTreeSelect
            name="sale"
            label="转移至"
            request={async () => {
              return sales
            }}
            fieldProps={{
              treeDefaultExpandAll: true,
              suffixIcon: null,
              filterTreeNode: true,
              popupMatchSelectWidth: false,
              autoClearSearchValue: true,
              multiple: false,
              treeNodeFilterProp: 'title',
              fieldNames: {
                label: 'title',
              },
            }}
          />
        </ModalForm>
      </Spin>
    </PageContainer>
  )
}

export default CustomerManage
